import Foundation

// 自动引用计数相关

class Person {
    let name: String
    init(name: String) {
        self.name = name
        print("\(name) is being initialized")
    }
    
    deinit {
        print("\(name) is being deinitialized")
    }
}

public func arcDemo_1() {
    var reference1: Person?
    var reference2: Person?
    var reference3: Person?
    
    reference1 = Person(name: "John Appleseed")
    print("初始化1个")
    reference2 = reference1
    reference3 = reference1
    print("2个强引用结束")
}



// MARK: - 实例间的循环强引用
class Apartment {
    let unit: String
    init(unit: String) {
        self.unit = unit
    }
    var tenant: Person_2?
    deinit { print("Apartment \(unit) is being deinitialized") }
}

class Person_2 {
    let name: String
    init(name: String) {
        self.name = name
    }
//    var apartment: Apartment?
    weak var apartment: Apartment?
    deinit { print("\(name) is being deinitialized") }
}

public func arcDemo_2() {
    var john: Person_2? = Person_2(name: "John Applessed")
    var unit4A: Apartment? = Apartment(unit: "4A")
    
    // 1. john.paratment -> unit4A
    john?.apartment = unit4A
    // 2. unit4A?.tenant -> john
    unit4A?.tenant = john
    // 3. 产生循环强引用
    
//    unit4A.tenant = nil
    
    // 这种方式无法消除循环引用
    john = nil
    unit4A = nil
    print("执行完毕")
}

// MARK: - 解决实例之间的循环引用
/// 1. 弱引用weak reference
/// 2. 无主引用unowned reference




